package com.corpgovernment.job.service;

import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.organization.model.base.PageInfoResponse;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.ListJobByConditionVO;
import com.corpgovernment.api.organization.model.org.front.ListOrgTreeRequest;
import com.corpgovernment.api.organization.model.org.request.ListJobByConditionRequest;
import com.corpgovernment.api.organization.model.org.response.ListJobByConditionResponse;
import com.corpgovernment.api.organization.model.post.ListPostByConditionVO;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.job.controller.vo.job.ListUsableJobReqVo;
import com.corpgovernment.job.controller.vo.job.ListUsableJobRespVo;
import com.corpgovernment.job.controller.vo.job.CreateJobReqVo;
import com.corpgovernment.job.controller.vo.job.DeleteJobReqVo;
import com.corpgovernment.job.controller.vo.job.PageJobReqVo;
import com.corpgovernment.job.controller.vo.job.PageJobRespVo;
import com.corpgovernment.job.controller.vo.job.UpdateJobReqVo;
import com.corpgovernment.job.dao.dataobject.OrgInfoDo;
import com.corpgovernment.job.dao.entity.db.EmployeeJobRelationDo;
import com.corpgovernment.job.dao.entity.db.JobDo;
import com.corpgovernment.job.dao.entity.db.JobOrgRelationDo;
import com.corpgovernment.job.dao.entity.db.JobTypeDo;
import com.corpgovernment.job.dao.mapper.EmployeeJobRelationMapper;
import com.corpgovernment.job.dao.mapper.JobMapper;
import com.corpgovernment.job.dao.mapper.JobOrgRelationMapper;
import com.corpgovernment.job.dao.mapper.JobTypeMapper;
import com.corpgovernment.job.service.bo.CheckJobResultBo;
import com.corpgovernment.job.service.bo.JobBo;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.controller.OrganizationController;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbUserOrgRelation;
import com.corpgovernment.organization.mapper.MbOrgInfoMapper;
import com.corpgovernment.organization.mapper.MbUserOrgRelationMapper;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.IUserOrgRelationService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author ldma
 * @date 2024/1/2
 */
@Service
@Slf4j
public class JobService {

    @Resource
    private JobMapper jobMapper;
    @Resource
    private JobTypeMapper jobTypeMapper;
    @Resource
    private EmployeeJobRelationMapper employeeJobRelationMapper;
    @Resource
    private JobOrgRelationMapper jobOrgRelationMapper;
    @Resource
    private MbOrgInfoMapper mbOrgInfoMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private OrganizationController organizationController;
    @Autowired
    private MbUserOrgRelationMapper userOrgRelationMapper;
    @Autowired
    private IUserOrgRelationService userOrgRelationService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;

    public void createJob(CreateJobReqVo requestParam, BaseUserInfo baseUserInfo) {
        // 前置校验
        StringBuilder sb = new StringBuilder();
        // 岗位名称校验
        checkJobName(requestParam.getJobName(), null, sb);
        // 岗位编号校验
        checkJobCode(requestParam.getJobCode(), null, sb);
        // 组织校验
        checkOrgId(requestParam.getOrgIdList(), Optional.ofNullable(baseUserInfo).orElse(new BaseUserInfo()), sb);
        // 岗位类型校验
        checkJobTypeId(requestParam.getJobTypeId(), sb);
        String errorMsg = sb.toString();
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR.code(), errorMsg.substring(0, errorMsg.length()-1));
        }

        // 保存岗位
        transactionTemplate.execute(status -> {
            JobDo jobDo = new JobDo(requestParam);
            jobMapper.create(jobDo);
            List<String> orgIdList = requestParam.getOrgIdList();
            if (CollectionUtils.isNotEmpty(orgIdList)) {
                jobOrgRelationMapper.batchCreate(orgIdList.stream().map(item -> new JobOrgRelationDo(jobDo.getId(), item)).collect(Collectors.toList()));
            }
            return null;
        });
    }

    /**
     * 设置uid的jobId为null
     * @param uid
     */
    public void removeJobIdByUid(String uid){
        if (StrUtil.isBlank(uid)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_JOBID_NULL);
        }
        employeeJobRelationMapper.removeByUid(uid);
    }

    public void deleteJob(DeleteJobReqVo requestParam) {
        Long jobId = requestParam.getJobId();
        if (jobId == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.REQUEST_PARAM_ERROR);
        }
        transactionTemplate.execute(transactionStatus -> {
            // 删除岗位
            jobMapper.removeById(jobId);
            // 删除岗位组织关系
            jobOrgRelationMapper.removeByJobId(jobId);
            // 删除员工岗位关系
            employeeJobRelationMapper.removeByJobId(jobId);
            return null;
        });
    }

    public void updateJob(UpdateJobReqVo requestParam, BaseUserInfo baseUserInfo) {
        // 前置校验
        StringBuilder sb = new StringBuilder();
        Long jobId = requestParam.getJobId();
        List<String> orgIdList = requestParam.getOrgIdList();
        if (jobId == null) {
            sb.append("传参有误jobId；");
        } else {
            // 岗位名称校验
            checkJobName(requestParam.getJobName(), jobId, sb);
            // 岗位编号校验
            checkJobCode(requestParam.getJobCode(), jobId, sb);
            // 组织校验
            checkOrgId(requestParam.getOrgIdList(), Optional.ofNullable(baseUserInfo).orElse(new BaseUserInfo()), sb);
            // 岗位类型校验
            checkJobTypeId(requestParam.getJobTypeId(), sb);
        }
        String errorMsg = sb.toString();
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR.code(), errorMsg.substring(0, errorMsg.length()-1));
        }

        // 员工组织不属于岗位所属范围的关系删除
        List<String> removeRelationUidList = getRemoveRelationUidList(jobId, orgIdList);

        transactionTemplate.execute(status -> {
            // 更新岗位
            jobMapper.update(new JobDo(requestParam));
            // 删除岗位组织关系
            jobOrgRelationMapper.removeByJobId(jobId);
            // 新增岗位组织关系
            if (CollectionUtils.isNotEmpty(orgIdList)) {
                jobOrgRelationMapper.batchCreate(orgIdList.stream().map(item -> new JobOrgRelationDo(jobId, item)).collect(Collectors.toList()));
            }
            // 删除员工与岗位的关系
            if (CollectionUtils.isNotEmpty(removeRelationUidList)) {
                employeeJobRelationMapper.removeByUidListAndJobId(removeRelationUidList, jobId);
            }
            return null;
        });
    }

    private List<String> getRemoveRelationUidList(Long jobId, List<String> orgIdList) {
        List<String> removeRelationUidList = new ArrayList<>(0);
        // 岗位无所属组织，即都适用
        if (CollectionUtils.isEmpty(orgIdList)) {
            return removeRelationUidList;
        }
        // 获取员工与岗位关系
        List<EmployeeJobRelationDo> employeeJobRelationDoList = employeeJobRelationMapper.listByJobIdList(Collections.singletonList(jobId));
        log.info("员工与岗位关系 employeeJobRelationDoList={}", employeeJobRelationDoList);
        if (CollectionUtils.isEmpty(employeeJobRelationDoList)) {
            return removeRelationUidList;
        }
        // 获取员工所属组织
        List<MbUserOrgRelation> userOrgRelationList = userOrgRelationService.findByUids(employeeJobRelationDoList.stream().map(EmployeeJobRelationDo::getUid).collect(Collectors.toList()));
        Map<String, String> uidOrgIdMap = convert(userOrgRelationList);
        Set<String> usableOrgIdSet = new HashSet<>(orgIdList);
        log.info("员工所属组织userOrgRelationList={} uidOrgIdMap={} 可用组织usableOrgIdSet={}", userOrgRelationList, uidOrgIdMap, usableOrgIdSet);
        for (EmployeeJobRelationDo item : employeeJobRelationDoList) {
            String uid = item.getUid();
            String orgId = uidOrgIdMap.get(uid);
            // 不属于所属组织则删除
            if (!usableOrgIdSet.contains(orgId)) {
                removeRelationUidList.add(uid);
            }
        }
        log.info("removeRelationUidList={}", removeRelationUidList);
        return removeRelationUidList;
    }

    private Map<String, String> convert(List<MbUserOrgRelation> userOrgRelationList) {
        Map<String, String> uidOrgIdMap = new HashMap<>();
        for (MbUserOrgRelation item : userOrgRelationList) {
            uidOrgIdMap.put(item.getUid(), item.getOrgId());
        }
        return uidOrgIdMap;
    }

    public PageJobRespVo pageJob(PageJobReqVo requestParam) {
        PageJobRespVo result = new PageJobRespVo();
        // 查询所有岗位
        List<JobDo> jobDoList;
        Long jobTypeId = requestParam.getJobTypeId();
        if (jobTypeId == null) {
            jobDoList = jobMapper.listAll();
        } else {
            jobDoList = jobMapper.listByJobTypeId(requestParam.getJobTypeId());
        }
        if (CollectionUtils.isEmpty(jobDoList)) {
            return result;
        }
        List<Long> jobIdList = jobDoList.stream().map(JobDo::getId).collect(Collectors.toList());
        // 查询岗位组织关系
        List<JobOrgRelationDo> jobOrgRelationDoList = jobOrgRelationMapper.listByJobIdList(jobIdList);
        Map<Long, List<String>> jobOrgRelationMap = jobOrgRelationDoList
                .stream().collect(Collectors.groupingBy(JobOrgRelationDo::getJobId, Collectors.mapping(JobOrgRelationDo::getOrgId, Collectors.toList())));
        List<String> orgIdList = jobOrgRelationDoList.stream().map(JobOrgRelationDo::getOrgId).distinct().collect(Collectors.toList());
        // 查询岗位类型 岗位类型id：岗位类型
        Map<Long, JobTypeDo> jobTypeMap = jobTypeMapper.listByIdList(jobDoList.stream().map(JobDo::getJobTypeId).distinct().collect(Collectors.toList()))
                .stream().collect(Collectors.toMap(JobTypeDo::getId, item -> item, (a,b)->a));
        // 查询员工数量 岗位id：员工数量
        List<EmployeeJobRelationDo> employeeJobRelationDos = employeeJobRelationMapper.listByJobIdList(jobIdList);
        List<String> normalEmployeeList = new ArrayList<>(0);
        if (CollectionUtils.isNotEmpty(employeeJobRelationDos)) {
            // 查询在职员工
            normalEmployeeList = userOrgRelationMapper.listByUids(employeeJobRelationDos.stream().map(EmployeeJobRelationDo::getUid).distinct().collect(Collectors.toList())).stream().map(MbUserOrgRelation::getUid).collect(Collectors.toList());
        }
        // 过滤非正常员工并转成map
        Set<String> normalEmployeeSet = new HashSet<>(normalEmployeeList);
        Map<Long, Long> jobIdEmployeeCountMap = employeeJobRelationDos.stream().filter(item -> normalEmployeeSet.contains(item.getUid())).collect(Collectors.groupingBy(EmployeeJobRelationDo::getJobId, Collectors.counting()));
        // 查询组织名称 组织id：组织
        List<MbOrgInfo> orgInfoList = new ArrayList<>(0);
        if (CollectionUtils.isNotEmpty(orgIdList)) {
            Example example = new Example(MbOrgInfo.class);
            example.createCriteria().andIn("orgId", orgIdList).andEqualTo("deleteTime", new Date(0));
            orgInfoList = mbOrgInfoMapper.selectByExample(example);
        }
        Map<String, MbOrgInfo> orgInfoMap = orgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, item -> item, (a,b)->a));
        // 构建返回结果
        List<PageJobRespVo.Job> jobList = jobDoList.stream().map(item -> new PageJobRespVo.Job(item, jobTypeMap, jobIdEmployeeCountMap, orgInfoMap, jobOrgRelationMap)).collect(Collectors.toList());
        List<String> jobOrgIdList = requestParam.getJobOrgIdList();
        // 组织筛选
        if (CollectionUtils.isNotEmpty(jobOrgIdList)) {
            Set<String> jobOrgIdSet = new HashSet<>(jobOrgIdList);
            jobList = jobList.stream().filter(item -> {
                List<PageJobRespVo.JobOrg> jobOrgList = item.getJobOrgList();
                return CollectionUtils.isNotEmpty(jobOrgList) && jobOrgList.stream().anyMatch(jobOrg -> jobOrgIdSet.contains(jobOrg.getJobOrgId()));
            }).collect(Collectors.toList());
        }
        // 分页
        result.setJobCount(jobList.size());
        result.setJobList(jobList.subList((requestParam.getPageNum()-1)*requestParam.getPageSize(), Math.min(requestParam.getPageNum()*requestParam.getPageSize(), jobList.size())));
        return result;
    }

    public List<OrgInfoDo> listUsableOrg(BaseUserInfo baseUserInfo) {
        ListOrgTreeRequest listOrgTreeRequest = new ListOrgTreeRequest();
        listOrgTreeRequest.setShowLevelText(false);
        JSONResult<List<GetOrgTreeResponse>> result = organizationController.listOrgTree(listOrgTreeRequest, Optional.ofNullable(baseUserInfo).orElse(new BaseUserInfo()));
        if (result == null || result.getData() == null) {
            return new ArrayList<>(0);
        }
        List<OrgInfoDo> orgInfoDoList = new ArrayList<>(32);
        result.getData().forEach(item -> recurOrgTree(item, orgInfoDoList, 1));
        return orgInfoDoList.stream().distinct().collect(Collectors.toList());
    }

    public void recurOrgTree(GetOrgTreeResponse getOrgTreeResponse, List<OrgInfoDo> orgInfoDoList, int level) {
        if (level > 100) {
            return;
        }
        orgInfoDoList.add(new OrgInfoDo(getOrgTreeResponse.getOrgId(), getOrgTreeResponse.getLabel(), getOrgTreeResponse.getBusinessCode()));
        if (CollectionUtils.isNotEmpty(getOrgTreeResponse.getChildren())) {
            getOrgTreeResponse.getChildren().forEach(item -> recurOrgTree(item, orgInfoDoList, level+1));
        }
    }

    public ListUsableJobRespVo listUsableJob(ListUsableJobReqVo listUsableJobReqVo, BaseUserInfo baseUserInfo) {
        String orgId = listUsableJobReqVo.getOrgId();
        // 获取所有岗位
        List<JobDo> jobDoList = jobMapper.listAll();
        // 获取所有岗位类型
        Map<Long, JobTypeDo> jobTypeDoMap = jobTypeMapper.listAll().stream().collect(Collectors.toMap(JobTypeDo::getId, item -> item, (a,b)->a));
        // 获取所有岗位组织关系
        Map<Long, List<String>> jobOrgRelationMap = jobOrgRelationMapper.listAll()
                .stream().collect(Collectors.groupingBy(JobOrgRelationDo::getJobId, Collectors.mapping(JobOrgRelationDo::getOrgId, Collectors.toList())));
        // 根据组织过滤岗位
        // 帐号数据权限可见范围组织
        if (StringUtils.isBlank(orgId)) {
            Set<String> orgIdSet = listUsableOrg(baseUserInfo).stream().map(OrgInfoDo::getOrgId).collect(Collectors.toSet());
            jobDoList = jobDoList.stream().filter(item -> {
                Long jobId = item.getId();
                List<String> jobOrgIdList = jobOrgRelationMap.get(jobId);
                return CollectionUtils.isEmpty(jobOrgIdList) || jobOrgIdList.stream().anyMatch(orgIdSet::contains);
            }).collect(Collectors.toList());
        }
        // 员工可见范围是自己的所属组织
        else {
            jobDoList = jobDoList.stream().filter(item -> {
                Long jobId = item.getId();
                List<String> jobOrgIdList = jobOrgRelationMap.get(jobId);
                return CollectionUtils.isEmpty(jobOrgIdList) || jobOrgIdList.stream().anyMatch(orgId::equals);
            }).collect(Collectors.toList());
        }
        // 模糊搜索
        String key = listUsableJobReqVo.getKey();
        if (StringUtils.isNotBlank(key)) {
            jobDoList = jobDoList.stream().filter(item -> item.getName().toLowerCase().contains(key.toLowerCase())).collect(Collectors.toList());
        }
        // 转成vo
        List<ListUsableJobRespVo.JobTypeVo> jobTypeVoList = new ArrayList<>(jobTypeDoMap.size());
        jobDoList.stream().collect(Collectors.groupingBy(JobDo::getJobTypeId)).forEach((k, v) -> {
            if (CollectionUtils.isEmpty(v)) {
                return;
            }
            JobTypeDo jobTypeDo = jobTypeDoMap.get(k);
            List<ListUsableJobRespVo.JobVo> jobVoList = v.stream().map(item -> new ListUsableJobRespVo.JobVo(item.getId(), item.getName(), item.getCode())).collect(Collectors.toList());
            jobTypeVoList.add(new ListUsableJobRespVo.JobTypeVo(jobTypeDo.getId(), jobTypeDo.getName(), jobVoList));
        });
        List<ListUsableJobRespVo.JobVo> jobVoList = jobDoList.stream().map(item -> new ListUsableJobRespVo.JobVo(item.getId(), item.getName(), item.getCode())).collect(Collectors.toList());
        return new ListUsableJobRespVo(jobTypeVoList, jobVoList);
    }

    private void checkJobName(String jobName, Long jobId, StringBuilder sb) {
        if (StringUtils.isBlank(jobName)) {
            sb.append("岗位名称不能为空；");
        } else {
            if (jobName.length() > 20) {
                sb.append("岗位名称限20字符以内；");
            }
            JobDo jobDo = jobMapper.getByName(jobName);
            if (jobDo != null && !jobDo.getId().equals(jobId)) {
                sb.append("岗位名称不唯一；");
            }
        }
    }

    private void checkJobCode(String jobCode, Long jobId, StringBuilder sb) {
        if (StringUtils.isNotBlank(jobCode)) {
            if (jobCode.length() > 20) {
                sb.append("岗位编号限20字符以内；");
            }
            JobDo jobDo = jobMapper.getByCode(jobCode);
            if (jobDo != null && !jobDo.getId().equals(jobId)) {
                sb.append("岗位编号不唯一；");
            }
        }
    }

    private void checkOrgId(List<String> orgIdList, BaseUserInfo baseUserInfo, StringBuilder sb) {
        checkOrgId(orgIdList, listUsableOrg(baseUserInfo).stream().map(OrgInfoDo::getOrgId).collect(Collectors.toSet()), sb);
    }

    private void checkOrgId(List<String> orgIdList, Set<String> orgIdSet, StringBuilder sb) {
        if (CollectionUtils.isNotEmpty(orgIdList)) {
            orgIdList.forEach(item -> {
                if (!orgIdSet.contains(item)) {
                    sb.append("orgId=").append(item).append("不可用；");
                }
            });
        }
    }

    private void checkJobTypeId(Long jobTypeId, StringBuilder sb) {
        if (jobTypeId != null && jobTypeMapper.getById(jobTypeId) == null) {
            sb.append("岗位类型不存在；");
        }
    }

    public CheckJobResultBo checkJobNameAndJobCode(String jobName, String jobCode, String orgId, String uid, Map<String, JobBo> jobNameMap, Map<String, JobBo> jobCodeMap) {
        // 长度校验
        if (StringUtils.isNotBlank(jobName) && jobName.length() > 20) {
            return new CheckJobResultBo("岗位名称限20字符以内", null, null);
        }
        if (StringUtils.isNotBlank(jobCode) && jobCode.length() > 20) {
            return new CheckJobResultBo("岗位编号限20字符以内", null, null);
        }
        // 如果岗位名称填了，岗位编号没填
        if (StringUtils.isNotBlank(jobName) && StringUtils.isBlank(jobCode)) {
            JobBo jobBo = jobNameMap.get(jobName);
            // 存在则关联
            if (jobBo != null) {
                return checkJobOrgScope(jobBo, uid, orgId);
            }
            // 不存在创建岗位并关联
            JobDo jobDo = new JobDo();
            jobDo.setName(jobName);
            jobMapper.create(jobDo);
            jobNameMap.put(jobName, new JobBo(jobDo.getId(), jobName, "", null, jobDo.getJobTypeId()));
            return new CheckJobResultBo("", uid, jobDo.getId());
        }
        // 如果岗位名称没填，岗位编号填了
        if (StringUtils.isBlank(jobName) && StringUtils.isNotBlank(jobCode)) {
            JobBo jobBo = jobCodeMap.get(jobCode);
            // 存在则关联
            if (jobBo != null) {
                return checkJobOrgScope(jobBo, uid, orgId);
            }
            // 不存在返回导入失败
            return new CheckJobResultBo("岗位不存在", null, null);
        }
        // 如果岗位名称和岗位编号都填了
        if (StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(jobCode)) {
            JobBo jobNameBO = jobNameMap.get(jobName);
            JobBo jobCodeBo = jobCodeMap.get(jobCode);
            // 岗位名称和岗位编号都存在
            if (jobNameBO != null && jobCodeBo != null) {
                // 如果岗位名称和岗位编号都一样，就关联
                if (jobCode.equals(jobNameBO.getCode())) {
                    return checkJobOrgScope(jobNameBO, uid, orgId);
                }
                // 如果岗位名称和岗位编号不一样，就返回导入失败
                return new CheckJobResultBo("岗位不存在", null, null);
            }
            // 岗位名称存在，岗位编号不存在，校验失败
            if (jobNameBO != null && jobCodeBo == null) {
                return new CheckJobResultBo("岗位不存在", null, null);
            }
            // 岗位名称不存在，岗位编号存在，校验失败
            if (jobNameBO == null && jobCodeBo != null) {
                return new CheckJobResultBo("岗位不存在", null, null);
            }
            // 岗位名称和岗位编号都不存在，就创建岗位并关联
            if (jobNameBO == null && jobCodeBo == null) {
                // 岗位名称和岗位编号都不存在，就创建岗位并关联
                JobDo jobDo = new JobDo();
                jobDo.setName(jobName);
                jobDo.setCode(jobCode);
                jobMapper.create(jobDo);
                jobNameMap.put(jobName, new JobBo(jobDo.getId(), jobName, jobCode, null, jobDo.getJobTypeId()));
                jobCodeMap.put(jobCode, new JobBo(jobDo.getId(), jobName, jobCode, null, jobDo.getJobTypeId()));
                return new CheckJobResultBo("", uid, jobDo.getId());
            }
        }
        // 如果都没填，就不关联
        if (StringUtils.isBlank(jobName) && StringUtils.isBlank(jobCode)) {
            return new CheckJobResultBo();
        }
        return null;
    }

    public List<JobBo> listAllJobBo() {
        List<JobDo> jobDoList = jobMapper.listAll();
        if (CollectionUtils.isEmpty(jobDoList)) {
            return new ArrayList<>(0);
        }
        // 查询岗位组织关系
        List<JobOrgRelationDo> jobOrgRelationDoList = jobOrgRelationMapper.listAll();
        Map<Long, List<String>> jobOrgRelationMap = jobOrgRelationDoList
                .stream().collect(Collectors.groupingBy(JobOrgRelationDo::getJobId, Collectors.mapping(JobOrgRelationDo::getOrgId, Collectors.toList())));
        return jobDoList.stream().map(item -> new JobBo(item.getId(), item.getName(), item.getCode(), jobOrgRelationMap.get(item.getId()), item.getJobTypeId())).collect(Collectors.toList());
    }

    public List<JobDo> listJobBoByOrgId(String orgId) {
        // 查询岗位组织关系
        List<JobOrgRelationDo> jobOrgRelationDoList = jobOrgRelationMapper.listJobByOrgId(orgId);
        if(CollectionUtils.isEmpty(jobOrgRelationDoList)){
            return Collections.emptyList();
        }
        List<Long> idList = jobOrgRelationDoList.stream().map(JobOrgRelationDo::getJobId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(idList)){
            return Collections.emptyList();
        }
        return jobMapper.listByIdList(idList);
    }


    public ListJobByConditionResponse listJobByCondition(ListJobByConditionRequest request, BaseUserInfo baseUserInfo){
        ListJobByConditionResponse response = new ListJobByConditionResponse();
        List<ListJobByConditionVO> jobList = CollectionUtils.newArrayList();
        // 查询全量岗位信息
        List<JobDo> jobInfoList = jobMapper.listAll();

        // 根据搜索条件进行过滤
        if (StringUtils.isNotBlank(request.getQuery())){
            List<JobDo> jobNameList = jobInfoList.stream().filter(e -> StringUtils.isNotBlank(e.getName())).filter(e -> e.getName().contains(request.getQuery())).collect(Collectors.toList());
            List<JobDo> jobCodeList = jobInfoList.stream().filter(e -> StringUtils.isNotBlank(e.getCode())).filter(e -> e.getCode().contains(request.getQuery())).collect(Collectors.toList());
            jobNameList.addAll(jobCodeList);
            jobInfoList = jobNameList.stream().distinct().collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(jobInfoList)){
            response.setJobList(jobList);
            return response;
        }

        // 查询岗位组织关联关系
        List<Long> jobIdList = jobInfoList.stream().map(JobDo::getId).collect(Collectors.toList());
        List<JobOrgRelationDo> jobOrgRelationDoList = jobOrgRelationMapper.listByJobIdList(jobIdList);
        Map<Long, List<String>> jobOrgRelationMap = jobOrgRelationDoList
                .stream().collect(Collectors.groupingBy(JobOrgRelationDo::getJobId, Collectors.mapping(JobOrgRelationDo::getOrgId, Collectors.toList())));

        // 根据数据权限过滤组织信息
        List<String> orgIdList = jobOrgRelationDoList.stream().map(JobOrgRelationDo::getOrgId).distinct().collect(Collectors.toList());
        List<MbOrgInfo> orgInfoList = mbOrgInfoMapper.listByOrgIds(orgIdList);
        orgInfoList = organizationInfoService.filterByRole(orgInfoList, baseUserInfo);
        orgIdList = orgInfoList.stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList());

        // 过滤岗位，组装信息
        List<String> finalOrgIdList = orgIdList;
        jobInfoList.forEach(e ->{
            List<String> orgIds = Optional.ofNullable(jobOrgRelationMap.get(e.getId())).orElse(CollectionUtils.newArrayList());
            AtomicBoolean add = new AtomicBoolean(false);
            orgIds.forEach(k ->{
                if (finalOrgIdList.contains(k)){
                    add.set(true);
                }
            });
            if (add.get()){
                ListJobByConditionVO vo = new ListJobByConditionVO();
                vo.setJobId(e.getId().toString());
                vo.setJobCode(e.getCode());
                vo.setJobName(e.getName());
                jobList.add(vo);
            }
        });
        // 处理分页
        return pageJobList(request, response, jobList);
    }

    private ListJobByConditionResponse pageJobList(ListJobByConditionRequest request, ListJobByConditionResponse response, List<ListJobByConditionVO> jobList) {
        PageInfoResponse pageInfo = request.getPageInfo();
        // 无分页信息则全部返回
        if (Objects.isNull(pageInfo) || Objects.isNull(pageInfo.getPageNum()) || Objects.isNull(pageInfo.getPageSize())){
            response.setJobList(jobList);
            return response;
        }
        int pageSize = pageInfo.getPageSize();
        int pageNum = pageInfo.getPageNum();
        int count = jobList.size();
        int totalPage = (count + pageSize - 1) / pageSize;
        pageInfo.setCount(count);
        pageInfo.setTotalPage(totalPage);
        response.setPageInfo(pageInfo);
        // 超页返回空
        if (pageNum > totalPage){
            response.setJobList(CollectionUtils.newArrayList());
        } else {
            List<ListJobByConditionVO> subList = jobList.stream().skip((long) (pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            response.setJobList(subList);
        }
        return response;
    }

    public Map<String, JobDo> getUidJobMap(List<String> uidList) {
        List<EmployeeJobRelationDo> employeeJobRelationDoList = employeeJobRelationMapper.listByUidList(uidList);
        if (CollectionUtils.isEmpty(employeeJobRelationDoList)) {
            return Collections.emptyMap();
        }
        Map<String, EmployeeJobRelationDo> employeeJobRelationDoMap = employeeJobRelationDoList.stream().collect(Collectors.toMap(EmployeeJobRelationDo::getUid, item -> item, (a,b)->a));
        Map<Long, JobDo> jobDoMap = jobMapper.listByIdList(employeeJobRelationDoList.stream().map(EmployeeJobRelationDo::getJobId).distinct().collect(Collectors.toList())).stream().collect(Collectors.toMap(JobDo::getId, item -> item, (a,b)->a));
        if (CollectionUtils.isEmpty(employeeJobRelationDoMap) || CollectionUtils.isEmpty(jobDoMap)) {
            return Collections.emptyMap();
        }
        Map<String, JobDo> uidJobMap = new HashMap<>();
        employeeJobRelationDoList.forEach(relation -> {
            String uid = relation.getUid();
            Long jobId = relation.getJobId();
            JobDo jobDo = jobDoMap.get(jobId);
            if (jobDo != null) {
                uidJobMap.put(uid, jobDo);
            }
        });
        return uidJobMap;
    }

    private CheckJobResultBo checkJobOrgScope(JobBo jobBo, String uid, String orgId) {
        if (CollectionUtils.isEmpty(jobBo.getOrgIdList()) || jobBo.getOrgIdList().contains(orgId)) {
            return new CheckJobResultBo("", uid, jobBo.getId());
        }
        return new CheckJobResultBo("岗位不存在", null, null);
    }

}
